import { AfterViewInit, Component, ComponentFactoryResolver, Input, OnDestroy, OnInit, ViewChild } from '@angular/core';
import { AdComponent, AdItem } from '../base/hero.base';
import { AdDirective } from './Ad.directive';
import { AlertComponent } from './alert/alert.component';

@Component({
  selector: 'app-add-banner',
  standalone: true,
  template: `
  <div class="ad-banner">
                <h3>Advertisements</h3>
                <!-- hostElement 在此！ -->
                <ng-template appAd></ng-template>
              </div>
  `,
  styleUrls: []
})
export class AdBannerComponent implements OnInit, AfterViewInit, OnDestroy {

  @Input()
  ads!: AdItem[];
  currentAddIndex: number = -1;
  @ViewChild(AdDirective) adHost!: AdDirective;
  subscription: any;
  interval: any;

  constructor(private componentFactoryResolver: ComponentFactoryResolver) { }

  ngOnInit() {
    this.loadComponent();
    this.getAds();
  }
  getAds() {
    this.interval = setInterval(() => {
      this.loadComponent();
    }, 3000);
  }

  loadComponent() {
    this.currentAddIndex = (this.currentAddIndex + 1) % this.ads.length;
    let adItem = this.ads[this.currentAddIndex];

    // 这里使用了工厂模式。其实Angular对于模板中出现的每一个Component都会创建一个ComponentFactory。在创建销毁时
    // 实际上使用的是组件工厂来创建组件的新实例。
    let componentFactory = this.componentFactoryResolver.resolveComponentFactory(adItem.component);

    // let viewContainerRef = this.adHost.viewContainerRef;
    let viewContainerRef = this.adHost.viewContainerRef;
    viewContainerRef.clear();
    // 传入对应的组件工厂来创建新的组件，并保存新组建的引用。
    let componentRef = viewContainerRef.createComponent(componentFactory);
    // 绑定数据
    (<AdComponent>componentRef.instance).data = adItem.data;
  }


  ngAfterViewInit(): void {
    clearInterval(this.interval);
  }
  ngOnDestroy(): void {

  }

}
